package com.jsj.isdt.servlet;

import com.alibaba.fastjson.JSON;
import com.jsj.isdt.entity.User;
import com.jsj.isdt.utils.DBUtils;
import com.jsj.isdt.utils.ResultData;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.swing.*;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.*;

public class ServletLogin extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html;charset=utf-8");
        resp.setCharacterEncoding("utf-8");
       String action =req.getParameter("action")==null ? "":req.getParameter("action");
     switch (action){
          case "login":
               login(req,resp);
               break;
         case "login1":
             login1(req,resp);
             break;
            case "logout":
               logout(req ,resp);
                break;
         case "logout1":
             logout1(req ,resp);
             break;
         case "register":
             register(req ,resp);
             break;
         case "update":
             update(req ,resp);
             break;
         case "M":
            M(req ,resp);
             break;
            default:
                break;

        }
        resp.setContentType("text/html;Charset=utf-8");
        String username= req.getParameter("username");
        String password=req.getParameter("password");
        System.out.println(username + "" +password);
        String url = "jdbc:mysql://localhost:3306/demo?useUnicode=true&characterEncoding=UTF8&useSSL=true&serverTimezone=UTC";
        String dbusername = "root";
        String dbpassword = "123456";
       PrintWriter out = resp.getWriter();

        //1.加载驱动
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            Connection connection = DriverManager.getConnection(url, dbusername, dbpassword);
            String sql ="select * from user where username =? and password =?";
                      PreparedStatement pstmt = connection.prepareStatement(sql);
                             pstmt.setString(1,username);
                       pstmt.setString(2,password);
                      ResultSet rs = pstmt.executeQuery();
            System.out.println("数据库查询成功");
            ResultData rd =new ResultData();
            if (rs.next()){
                HttpSession session = req.getSession();
                session.setAttribute("username",username);
                rd.setCode("201");
                rd.setMsg("登录成功");
//                resp.sendRedirect("index.jsp");
            }
  else {  rd.setCode("4041");
                rd.setMsg("用户名密码有误");

//                resp.sendRedirect("login.jsp");
                //4.执行SQL的对象
            }
//            out.write(JSON.toJSONString(rd));
        } catch (Exception e) {

            System.out.println(e.getMessage());
        }

        //2.用户信息和URL

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req,resp);
    }
    private  void  login(HttpServletRequest req, HttpServletResponse resp) throws IOException{
        PrintWriter out = resp.getWriter();
        String username= req.getParameter("username");
        String password=req.getParameter("password");
        String validcode =req.getParameter("validcode");
        HttpSession session = req.getSession();
        ResultData rd =new ResultData();
        if (!session.getAttribute("piccode").toString().equals(validcode)){
            rd.setCode("401");
            rd.setMsg("验证码有误");
            out.write(JSON.toJSONString(rd));
            return;
        }
        System.out.println(username + "" +password);
        String url = "jdbc:mysql://localhost:3306/demo?useUnicode=true&characterEncoding=UTF8&useSSL=true&serverTimezone=UTC";
        String dbusername = "root";
        String dbpassword = "123456";
        //1.加载驱动
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            Connection connection = DriverManager.getConnection(url, dbusername, dbpassword);
            String sql ="select * from user where username =? and password =?";
            PreparedStatement pstmt = connection.prepareStatement(sql);
            pstmt.setString(1,username);
            pstmt.setString(2,password);
            ResultSet rs = pstmt.executeQuery();
            System.out.println("数据库查询成功");
            if (rs.next()){
                session.setAttribute("username",username);
                rd.setCode("201");
                rd.setMsg("登录成功");
            }
            else {
                rd.setCode("4041");
                rd.setMsg("用户名密码有误");
            }
            out.write(JSON.toJSONString(rd));
        } catch (Exception e) {

            System.out.println(e.getMessage());
        }

    }
    private void  logout(HttpServletRequest req, HttpServletResponse resp)throws IOException{
       HttpSession session =req.getSession(false);
       if (session !=null){
           session.removeAttribute("username");
           session.invalidate();
       }
       resp.sendRedirect("/login.jsp");
    }
    private void  logout1(HttpServletRequest req, HttpServletResponse resp)throws IOException{
        HttpSession session =req.getSession(false);
        if (session !=null){
            session.removeAttribute("username");
            session.invalidate();
        }
        resp.sendRedirect("/sirloin.jsp");
    }
    private void  register(HttpServletRequest req, HttpServletResponse resp)throws IOException{
        String id  =req.getParameter("id");
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String phonenum = req.getParameter("phonenum");
        String url = "jdbc:mysql://localhost:3306/demo?useUnicode=true&characterEncoding=UTF8&useSSL=true&serverTimezone=UTC";
        String dbusername = "root";
        String dbpassword = "123456";
        //1.加载驱动
        try {PrintWriter out = resp.getWriter();
            Class.forName("com.mysql.cj.jdbc.Driver");
            Connection connection = DriverManager.getConnection(url, dbusername, dbpassword);
            String sql ="insert into user(id,username,password,phonenum) values (?,?,?,?)";
            System.out.println("加入成功");
            PreparedStatement pstmt = connection.prepareStatement(sql);
            pstmt.setString(1,id);
            pstmt.setString(2,username);
            pstmt.setString(3,password);
            pstmt.setString(4,phonenum);
            ResultData rd = new ResultData();
            if (pstmt.executeUpdate() >0){

                rd.setCode("200");
                rd.setMsg("注册成功");

//                resp.sendRedirect("index.jsp");
            }
            else {

                rd.setCode("501");
                rd.setMsg("注册失败");
                //4.执行SQL的对象
            }
            out.write(JSON.toJSONString(rd));
        } catch (Exception e) {

            System.out.println(e.getMessage());
        }
    }
    private  void  update (HttpServletRequest req, HttpServletResponse resp) throws IOException  {
        resp.setCharacterEncoding("utf-8");
        try {
            PrintWriter out = resp.getWriter();
            String id = req.getParameter("id");
            String username =  new String(req.getParameter("username").getBytes("iso-8859-1"),"utf-8");
            String oldpassword =  new String(req.getParameter("oldpassword").getBytes("iso-8859-1"),"utf-8");
            String newpassword      =  new String(req.getParameter("newpassword").getBytes("iso-8859-1"),"utf-8");
            String sql = "update  ignore user set  password=? where id=? and username=? and password= ?";
            if (DBUtils.testDemoUpdate(sql,newpassword,id,username,oldpassword) > 0) {
                out.write(JSON.toJSONString(new ResultData(String.valueOf(resp.getStatus()), "修改成功")));
            } else {
                out.write(JSON.toJSONString(new ResultData("501", "用户名或ID或密码错误请重输")));
            }
        }
        catch (Exception e)
        {
            resp.getWriter().write(JSON.toJSONString(new ResultData("501", "数据有误无法保存")));
        }
    }
    private void  M(HttpServletRequest req, HttpServletResponse resp)throws IOException{
        String id = req.getParameter("id");
        String username =  new String(req.getParameter("username").getBytes("iso-8859-1"),"utf-8");
        String oldpassword =  new String(req.getParameter("oldpassword").getBytes("iso-8859-1"),"utf-8");
        String newpassword      =  new String(req.getParameter("newpassword").getBytes("iso-8859-1"),"utf-8");
        String url = "jdbc:mysql://localhost:3306/demo?useUnicode=true&characterEncoding=UTF8&useSSL=true&serverTimezone=UTC";
        String dbusername = "root";
        String dbpassword = "123456";
        //1.加载驱动
        try {PrintWriter out = resp.getWriter();
            Class.forName("com.mysql.cj.jdbc.Driver");
            Connection connection = DriverManager.getConnection(url, dbusername, dbpassword);
            String sql ="update set password=? where id=? and username=? and password=?";
            System.out.println("加入成功");
            PreparedStatement pstmt = connection.prepareStatement(sql);
            pstmt.setString(1,newpassword);
            pstmt.setString(2,id);
            pstmt.setString(3,username);
            pstmt.setString(4,oldpassword);
            ResultData rd = new ResultData();
            if (pstmt.executeUpdate() >0){

                rd.setCode("200");
                rd.setMsg("修改成功");

//                resp.sendRedirect("index.jsp");
            }
            else {

                rd.setCode("501");
                rd.setMsg("修改失败");

//                resp.sendRedirect("login.jsp");
                //4.执行SQL的对象
            }
            out.write(JSON.toJSONString(rd));
        } catch (Exception e) {

            System.out.println(e.getMessage());
        }
    }
    private  void  login1(HttpServletRequest req, HttpServletResponse resp) throws IOException{
        PrintWriter out = resp.getWriter();
        String username= req.getParameter("username");
        String password=req.getParameter("password");

        String validcode =req.getParameter("validcode");
        HttpSession session = req.getSession();
        ResultData rd =new ResultData();
        if (!session.getAttribute("piccode").toString().equals(validcode)){
            rd.setCode("401");
            rd.setMsg("验证码有误");
            out.write(JSON.toJSONString(rd));

            return;
        }

        System.out.println(username + "" +password);
        String url = "jdbc:mysql://localhost:3306/demo?useUnicode=true&characterEncoding=UTF8&useSSL=true&serverTimezone=UTC";
        String dbusername = "root";
        String dbpassword = "123456";
        //1.加载驱动
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            Connection connection = DriverManager.getConnection(url, dbusername, dbpassword);
            String sql ="select * from administrator where username =? and password =?";
            PreparedStatement pstmt = connection.prepareStatement(sql);
            pstmt.setString(1,username);
            pstmt.setString(2,password);
            ResultSet rs = pstmt.executeQuery();
            System.out.println("数据库查询成功");
            if (rs.next()){
                session.setAttribute("username",username);
                rd.setCode("201");
                rd.setMsg("登录成功");

//                resp.sendRedirect("index.jsp");
            }
            else {

                rd.setCode("4041");
                rd.setMsg("用户名密码有误");

//                resp.sendRedirect("login.jsp");
                //4.执行SQL的对象
            }
            out.write(JSON.toJSONString(rd));
        } catch (Exception e) {

            System.out.println(e.getMessage());
        }

    }
}
